package com.shuhua.taskServer.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shuhua.common.result.Result;
import com.shuhua.pojo.dto.TeamCreateDTO;
import com.shuhua.pojo.entity.Admin;
import com.shuhua.pojo.entity.Craftsman;
import com.shuhua.pojo.entity.Team;
import com.shuhua.pojo.entity.TeamMember;
import com.shuhua.pojo.vo.CraftsmanSimpleVO;
import com.shuhua.pojo.vo.TeamApplyVO;
import com.shuhua.pojo.vo.TeamDetailVO;
import com.shuhua.pojo.vo.TeamMemberVO;
import com.shuhua.pojo.vo.TeamWithLeaderVO;
import com.shuhua.taskServer.mapper.AdminMapper;
import com.shuhua.taskServer.mapper.TeamMapper;
import com.shuhua.taskServer.mapper.TeamMemberMapper;
import com.shuhua.taskServer.service.CraftsmanService;
import com.shuhua.taskServer.service.TeamMemberService;
import com.shuhua.taskServer.service.TeamService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 班组服务实现类
 */
@Service
@RequiredArgsConstructor
public class TeamServiceImpl extends ServiceImpl<TeamMapper, Team> implements TeamService {
    
    private final CraftsmanService craftsmanService;
    private final TeamMemberService teamMemberService;
    private final TeamMemberMapper teamMemberMapper;
    private final AdminMapper adminMapper;
    
    @Override
    public Result<Page<TeamApplyVO>> pageTeamApplies(Long current, Long size, Integer teamType, Integer state) {
        // 创建分页对象
        Page<Team> page = new Page<>(current, size);
        
        // 创建查询条件
        LambdaQueryWrapper<Team> queryWrapper = new LambdaQueryWrapper<>();
        
        // 如果指定了班组类型，添加类型过滤条件
        if (teamType != null) {
            queryWrapper.eq(Team::getTeamType, teamType);
        }
        
        // 如果指定了审核状态，添加状态过滤条件
        if (state != null) {
            queryWrapper.eq(Team::getState, state);
        }
        
        // 按创建时间降序排序
        queryWrapper.orderByDesc(Team::getCreatedAt);
        
        // 执行分页查询
        Page<Team> teamPage = page(page, queryWrapper);
        
        // 转换为TeamApplyVO
        List<TeamApplyVO> teamApplyVOList = new ArrayList<>();
        for (Team team : teamPage.getRecords()) {
            TeamApplyVO teamApplyVO = new TeamApplyVO();
            teamApplyVO.setTeam(team);
            
            // 查询申请人（班组长）信息
            Craftsman craftsman = craftsmanService.getById(team.getTeamLeaderId());
            if (craftsman != null) {
                // 转换为CraftsmanSimpleVO，不包含密码和敏感字段
                CraftsmanSimpleVO craftsmanSimpleVO = new CraftsmanSimpleVO();
                BeanUtils.copyProperties(craftsman, craftsmanSimpleVO);
                teamApplyVO.setTeamLeader(craftsmanSimpleVO);
            }
            
            teamApplyVOList.add(teamApplyVO);
        }
        
        // 创建结果分页对象
        Page<TeamApplyVO> resultPage = new Page<>(teamPage.getCurrent(), teamPage.getSize(), teamPage.getTotal());
        resultPage.setRecords(teamApplyVOList);
        
        return Result.success(resultPage);
    }
    
    @Override
    public Result<Page<TeamWithLeaderVO>> pageTeamsWithLeader(Long current, Long size, Integer teamType, String name) {
        // 创建分页对象
        Page<Team> page = new Page<>(current, size);
        
        // 创建查询条件
        LambdaQueryWrapper<Team> queryWrapper = new LambdaQueryWrapper<>();
        
        // 如果指定了班组类型，添加类型过滤条件
        if (teamType != null) {
            queryWrapper.eq(Team::getTeamType, teamType);
        }
        
        // 如果指定了班组名称，添加名称模糊查询条件
        if (name != null && !name.isEmpty()) {
            queryWrapper.like(Team::getName, name);
        }
        
        // 只查询审核通过的班组
        queryWrapper.eq(Team::getState, 1);
        
        // 按创建时间降序排序
        queryWrapper.orderByDesc(Team::getCreatedAt);
        
        // 执行分页查询
        Page<Team> teamPage = page(page, queryWrapper);
        
        // 转换为TeamWithLeaderVO
        List<TeamWithLeaderVO> teamWithLeaderVOList = new ArrayList<>();
        for (Team team : teamPage.getRecords()) {
            TeamWithLeaderVO teamWithLeaderVO = new TeamWithLeaderVO();
            teamWithLeaderVO.setTeam(team);
            
            // 查询班组长信息
            Craftsman teamLeader = craftsmanService.getById(team.getTeamLeaderId());
            if (teamLeader != null) {
                // 转换为CraftsmanSimpleVO，不包含密码和敏感字段
                CraftsmanSimpleVO craftsmanSimpleVO = new CraftsmanSimpleVO();
                BeanUtils.copyProperties(teamLeader, craftsmanSimpleVO);
                teamWithLeaderVO.setTeamLeader(craftsmanSimpleVO);
            }
            
            teamWithLeaderVOList.add(teamWithLeaderVO);
        }
        
        // 创建结果分页对象
        Page<TeamWithLeaderVO> resultPage = new Page<>(teamPage.getCurrent(), teamPage.getSize(), teamPage.getTotal());
        resultPage.setRecords(teamWithLeaderVOList);
        
        return Result.success(resultPage);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Team> createTeam(TeamCreateDTO teamCreateDTO) {
        // 验证工匠是否存在
        Craftsman craftsman = craftsmanService.getById(teamCreateDTO.getCraftsmanId());
        if (craftsman == null) {
            return Result.error("工匠不存在");
        }
        
        // 创建班组
        Team team = new Team();
        team.setTeamLeaderId(teamCreateDTO.getCraftsmanId());
        team.setTeamType(teamCreateDTO.getTeamType());
        team.setName(teamCreateDTO.getName());
        team.setIntroduction(teamCreateDTO.getIntroduction());
        team.setMemberNum(1); // 初始成员数为1（班组长自己）
        team.setCreatedAt(new Date());
        team.setState(0); // 设置为审核中状态
        
        // 保存班组信息
        boolean saved = save(team);
        if (!saved) {
            return Result.error("班组创建失败");
        }
        
        // 创建班组成员记录（班组长自动加入）
        TeamMember teamMember = new TeamMember();
        teamMember.setTeamId(team.getId());
        teamMember.setCraftsmanId(team.getTeamLeaderId());
        teamMember.setJoinTime(new Date());
        teamMemberService.save(teamMember);
        
        return Result.success("班组创建成功，等待管理员审核", team);
    }
    
    @Override
    public Result<Team> getTeamDetail(Long teamId) {
        Team team = getById(teamId);
        if (team == null) {
            return Result.error("班组不存在");
        }
        return Result.success(team);
    }
    
    @Override
    public Result<Object> getCraftsmanTeams(Long craftsmanId) {
        // 查询工匠创建的班组
        LambdaQueryWrapper<Team> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Team::getTeamLeaderId, craftsmanId);
        List<Team> teams = list(queryWrapper);
        
        return Result.success(teams);
    }
    
    @Override
    public Result<Page<Team>> pageTeams(Long current, Long size, Integer teamType, String name) {
        // 创建分页对象
        Page<Team> page = new Page<>(current, size);
        
        // 创建查询条件
        LambdaQueryWrapper<Team> queryWrapper = new LambdaQueryWrapper<>();
        
        // 如果指定了班组类型，添加类型过滤条件
        if (teamType != null) {
            queryWrapper.eq(Team::getTeamType, teamType);
        }
        
        // 如果指定了班组名称，添加名称模糊查询条件
        if (name != null && !name.isEmpty()) {
            queryWrapper.like(Team::getName, name);
        }
        
        // 只查询审核通过的班组
        queryWrapper.eq(Team::getState, 1);
        
        // 按创建时间降序排序
        queryWrapper.orderByDesc(Team::getCreatedAt);
        
        // 执行分页查询
        Page<Team> teamPage = page(page, queryWrapper);
        
        return Result.success(teamPage);
    }
    
    @Override
    public Result<TeamDetailVO> getTeamDetailWithMembers(Long teamId) {
        // 查询班组基本信息
        Team team = getById(teamId);
        if (team == null) {
            return Result.error("班组不存在");
        }
        
        // 创建班组详情VO
        TeamDetailVO teamDetailVO = new TeamDetailVO();
        teamDetailVO.setTeam(team);
        
        // 查询班组长信息
        TeamMemberVO leader = teamMemberMapper.findTeamLeaderByTeamId(teamId);
        teamDetailVO.setLeader(leader);
        
        // 查询班组成员信息
        List<TeamMemberVO> members = teamMemberMapper.findMemberDetailsByTeamId(teamId);
        teamDetailVO.setMembers(members);
        
        return Result.success(teamDetailVO);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Boolean> auditTeam(Long teamId, Integer state, Long adminId) {
        // 验证管理员是否存在
        Admin admin = adminMapper.selectById(adminId);
        if (admin == null) {
            return Result.error("管理员不存在");
        }
        
        // 验证班组是否存在
        Team team = getById(teamId);
        if (team == null) {
            return Result.error("班组不存在");
        }
        
        // 验证班组状态是否为审核中
        if (team.getState() != 0) {
            return Result.error("班组已审核，不能重复审核");
        }
        
        // 验证审核状态是否合法
        if (state != 1 && state != 2) {
            return Result.error("审核状态不合法");
        }
        
        // 更新班组状态
        team.setState(state);
        boolean updated = updateById(team);
        if (!updated) {
            return Result.error("审核失败");
        }
        
        // 如果审核通过，将班组长状态更新为班组长
        if (state == 1) {
            Craftsman craftsman = craftsmanService.getById(team.getTeamLeaderId());
            if (craftsman != null && craftsman.getIsTeamLeader() != 1) {
                craftsman.setIsTeamLeader(1);
                craftsmanService.updateById(craftsman);
            }
        }
        
        return Result.success("审核成功", true);
    }
} 